package com.pactera.asmp.server;

import cn.hutool.core.collection.CollectionUtil;
import com.pactera.asmp.server.common.websocket.SocketUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Set;

/**
 * 程序业务处理器
 *
 * @author zhangfei
 * @date 2025/1/17
 */
@Slf4j
@Component
public class AppServiceProcessor {

    @Autowired
    private RedisTemplate redisTemplate;

    @PostConstruct
    void init() {
        clearRedisCache();
    }

    @PreDestroy
    void destroy() {
        clearRedisCache();
    }

    /**
     * 程序启动后，将WS_开头的设备和大屏缓存全部清空，避免设备或前端的websocket连接缓存影响正常的逻辑
     */
    private void clearRedisCache() {
        log.info("清空所有设备和大屏的WebSocket缓存信息...");
        delAllKey(SocketUtil.REDIS_KEY_DEVICE_PREFIX);
        delAllKey(SocketUtil.REDIS_KEY_SCREEN_PREFIX);
    }

    private void delAllKey(String keyPrefix) {
        Set<String> keys = redisTemplate.keys(keyPrefix + "*");
        if (CollectionUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                redisTemplate.delete(key);
            }
        }
    }
}
